//
//  clipboard.swift
//  zcliperd
//
//  Created by 张宇飞的电脑 on 2019/9/5.
//  Copyright © 2019 zyf. All rights reserved.
//

import AppKit

class Clipboard {
    typealias Hook = (String) -> Void
    
    private let pasteboard = NSPasteboard.general
    private let timerInterval = 0.75
    
    private var changeCount: Int
    private var hooks: [Hook]
    private var timer: Timer?
    private var lastClipItem: String?
    
    init() {
        changeCount = pasteboard.changeCount
        hooks = []
        timer = nil
        lastClipItem = pasteboard.string(forType: NSPasteboard.PasteboardType.string)
    }
    
    func onNewCopy(_ hook: @escaping Hook) {
        hooks.append(hook)
        if lastClipItem != nil {
            hook(lastClipItem!)
        }
    }
    
    func startListening() {
        if timer != nil {
            return
        }
        timer = Timer.scheduledTimer(timeInterval: timerInterval,
                             target: self,
                             selector: #selector(checkPasteboard),
                             userInfo: nil,
                             repeats: true)
    }
    
    func stopListening() {
        timer?.invalidate()
    }

//    func copy(_ string: String) {
//        pasteboard.declareTypes([NSPasteboard.PasteboardType.string], owner: nil)
//        pasteboard.setString(string, forType: NSPasteboard.PasteboardType.string)
//    }

    @objc
    func checkPasteboard() {
        guard pasteboard.changeCount != changeCount else {
            return
        }
        
        if let lastItem = pasteboard.string(forType: NSPasteboard.PasteboardType.string) {
            for hook in hooks {
                hook(lastItem)
            }
        }
        
        changeCount = pasteboard.changeCount
    }
}
